<template>
  <div class="consumer-page activity-list-page">
    <!--头部标题-->
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'shopAdIndex' }">Shop</el-breadcrumb-item>
      <el-breadcrumb-item>New&Edit</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <!--serchBox-->
      <div class="search-box">
        <el-form :inline="true" label-position="top" :model="submitForm" size="mini" ref="submitForm" :rules="rules"
                 class="demo-ruleForm main-search-box">
          <!--数据库状态-->
          <!--新增状态下只显示active 且不可编辑-->
          <el-form-item label="Status" style="width: 200px;margin-right: 10px" v-if="isNewCreate">
            <el-select style="width: 200px;" class="editStyle" v-model="submitForm.status" disabled>
              <el-option v-for="i in newCreateStatusOption" :key="i.value" :label="i.label"
                         :value="i.value"></el-option>
            </el-select>
          </el-form-item>
          <!--编辑状态下显示所有的状态信息-->
          <el-form-item label="Status" style="width: 200px;margin-right: 10px" v-else>
            <el-select style="width: 200px;" class="editStyle" v-model="submitForm.status">
              <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 级联菜单 -->
          <!--第一级菜单-->
          <el-form-item label="Category1" style="width: 200px;margin-right: 10px" prop="firstCategory">
            <el-select style="width: 200px" v-model="submitForm.firstCategory" @change="getSecondaryData">
              <el-option v-for="i in categoryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
            </el-select>
          </el-form-item>
          <!--第二级菜单-->
          <el-form-item label="Category2" style="width: 200px;margin-right: 10px" prop="secondaryCategory">
            <el-select style="width: 200px" v-model="submitForm.secondaryCategory" @change="getThirdData"
            >
              <el-option v-for="i in secondaryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
            </el-select>
          </el-form-item>
          <!--第三级菜单-->
          <!--一级菜单 二级菜单肯定都是有的 三级菜单有就显示并校验 没有就隐藏 -->
          <el-form-item label="Category3" style="width: 200px;margin-right: 10px"
                        v-if="thirdData.length>0||submitForm.thirdCategory"
                        prop="thirdCategory">
            <el-select style="width: 200px" v-model="submitForm.thirdCategory" @change="getNewId">
              <el-option v-for="i in thirdData" :key="i.id" :label="i.name" :value="i.name"></el-option>
            </el-select>
          </el-form-item>
          <!-- 上传图片 -->
          <p class="upload-photos">Upload Photos</p>
          <div class="upload-box">
            <div style="text-align:left">
              <div class="photos-box">
                <div class="color-show">
                  <div v-if="showPhoto[0].url" class="color-box">
                    <img :src="showPhoto[0].url"/>
                    <a href="javascript:;" @click='delImage(0,showPhoto[0].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[0].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,0)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[1].url" class="color-box">
                    <img :src="showPhoto[1].url"/>
                    <a href="javascript:;" @click='delImage(1,showPhoto[1].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[1].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,1)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[2].url" class="color-box">
                    <img :src="showPhoto[2].url"/>
                    <a href="javascript:;" @click='delImage(2,showPhoto[2].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[2].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,2)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[3].url" class="color-box">
                    <img :src="showPhoto[3].url"/>
                    <a href="javascript:;" @click='delImage(3,showPhoto[3].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[3].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,3)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[4].url" class="color-box">
                    <img :src="showPhoto[4].url"/>
                    <a href="javascript:;" @click='delImage(4,showPhoto[4].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[4].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,4)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[5].url" class="color-box">
                    <img :src="showPhoto[5].url"/>
                    <a href="javascript:;" @click='delImage(5,showPhoto[5].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[5].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,5)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[6].url" class="color-box">
                    <img :src="showPhoto[6].url"/>
                    <a href="javascript:;" @click='delImage(6,showPhoto[6].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[6].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,6)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
                <div class="color-show">
                  <div v-if="showPhoto[7].url" class="color-box">
                    <img :src="showPhoto[7].url"/>
                    <a href="javascript:;" @click='delImage(7,showPhoto[7].id)'>
                      <span class="glyphicon glyphicon-remove"><i class="el-icon-delete"></i></span>
                    </a>
                  </div>
                  <div v-if="!showPhoto[7].url" class="color-box"
                       style="position: relative;top: 0;left: 0;z-index: 10;">
                    <label style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index:100;">
                      <input type="file" name="CoverImages" @change="getFile($event,7)" style="display: none;">
                    </label>
                    <span style="background: #fff; border: 1px solid #ddd; box-sizing: border-box;"
                          class="glyphicon glyphicon-remove"><i class="el-icon-plus"></i></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!--标题-->
          <el-row>
            <el-form-item label="Title" style="width: 200px;margin-right:10px" prop="title">
              <el-input
                type="textarea"
                :rows="4"
                v-model="submitForm.title"
                style="width:300px"
                maxlength="80">
              </el-input>
            </el-form-item>
          </el-row>
          <!--价格和单位-->
          <el-row>
            <el-form-item label="Price" style="width:150px;margin-right:10px" prop="price" class="price-require">
              <el-input v-model="submitForm.price"></el-input>
            </el-form-item>
            <el-form-item label="Unit" style="width: 200px;margin-right: 10px">
              <el-select style="width: 80px" v-model="submitForm.priceType">
                <el-option v-for="i in unitOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--状况-->
          <el-row>
            <el-form-item label="Condition" style="width: 200px;margin-right: 10px" prop="condition">
              <el-radio v-model="submitForm.condition" label="0">New</el-radio>
              <el-radio v-model="submitForm.condition" label="1">Used</el-radio>
            </el-form-item>
          </el-row>
          <!--描述-->
          <el-form-item label="Description" style="width: 200px;margin-right: 10px">
            <el-input
              type="textarea"
              :rows="4"
              v-model="submitForm.desc"
              style="width:300px"
              maxlength="1000">
            </el-input>
          </el-form-item>
          <!--位置-->
          <el-row>
            <el-form-item label="Region" prop="regionId">
              <el-select style="width: 200px" v-model="submitForm.regionId" @change="gettownships">
                <el-option v-for="rg in regions" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="Township" prop="townshipId">
              <el-select style="width: 200px" v-model="submitForm.townshipId">
                <el-option v-for="ts in townshipData" :key="ts.value" :label="ts.text" :value="ts.value"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--规格选择-->
          <el-row v-if="propertyData.length>0" v-for="item in propertyData" :key="item.id">
            <!--长度大于1就显示为下拉框-->
            <el-form-item v-if="item.values.length>1 || item.id == '55'" :label="item.name" style="width: 200px;margin-right: 10px">
              <el-select style="width: 200px" v-model="otherForm[item.id]"
                         @change="getModelData(item.id,otherForm[item.id])">
                <el-option v-for="i in item.values" :key="i.id" :label="i.text" :value="i.text"></el-option>
              </el-select>
            </el-form-item>
            <!--否则就显示成输入框-->
            <!--要对额外属性为Brand的输入框做字数限制 其他输入框不做限制-->
            <div v-else>
              <el-form-item v-if="item.name!=='Brand'" :label="item.name" style="width: 200px;">
                <el-input v-model="otherForm[item.id]"></el-input>
              </el-form-item>
              <!--限制字数50-->
              <el-form-item v-else label="Brand" style="width: 200px;" v-show="item.name='Brand'">
                <el-input v-model="otherForm[item.id]" placeholder="not exceed 50 characters" maxlength="50"></el-input>
              </el-form-item>
            </div>
          </el-row>
          <!--备注-->
          <el-form-item label="Notes" style="width: 200px;margin-right: 10px">
            <el-input
              type="textarea"
              :rows="4"
              v-model="submitForm.notes"
              style="width:300px">
            </el-input>
          </el-form-item>
          <!--提交信息或取消提交-->
          <el-row :gutter="40" type="flex" justify="center" style="padding:40px 0;">
            <el-col :span="6">
              <el-button @click.native="cancelPutForm" size="medium" style="width:100%" type="info">
                Cancel
              </el-button>
            </el-col>
            <el-col :span="6">
              <el-button @click.native="uploadSubmitForm"
                         size="medium" type="success" style="width:100%"
                         v-loading.fullscreen.lock="loadingImage">
                Save
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--list-->
    </div>
  </div>
</template>

<script>
  import categoryData from '@/json/category.json';
  import regions from '@/json/region';
  import townships from '@/json/township';
  import phoneBrand from '@/json/phoneBrand';
  import carBrand from '@/json/carBrand';

  import {
    uploadFormInfo,
    uploadShopAdPhotos,
    editFormInfo,
    getShopViewData,
    getBrandModelData
  } from '../../api/guc_api.js';
  import {getCarModelData} from  '../../api/zxy_api.js'
  import Qs from 'qs';


  export default {
    name: 'shopAdNew',
    data() {
      return {
        //用户id
        userId: '4',
        //显示图片的数组
        showPhoto: [
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
        ],
        //提交图片的数组
        uploadPhoto: [],
        // 需要提交的数据
        submitForm: {
          title: '',
          price: 0,
          regionId: 0,
          townshipId: 0,
          //仓库状态默认是active
          status: 1,
          //标题，价格，单位，状况 ，描述,备注
          title: '',
          price: '',
          priceType: '1',
          condition: '0',
          desc: '',
          notes: '',
          //位置
          regionId: '',
          townshipId: '',
          //商品规格数据
          values: [],
          categoryId: '',
          //额外添加的brand字段
          brand: '',
          //目录
          firstCategory: '',
          secondaryCategory: '',
          thirdCategory: '',
        },
        // 本地数据
        categoryData,
        regions,
        townships,
        phoneBrand,
        carBrand,
        secondaryData: [],
        thirdData: [],
        //属性数据
        propertyData: [],
        // 位置
        townshipData: [],
        selectedTownship: '',
        //仓库状态数据
        statusOption: [
          {
            label: 'Active',
            value: 1,
          },
          {
            label: 'Draft',
            value: 2,
          },
          {
            label: 'Sold',
            value: 3,
          },
          {
            label: 'Deleted',
            value: 4,
          },
          {
            label: 'Rejected',
            value: 5,
          },
          {
            label: 'Inactive',
            value: 6,
          },
          {
            label: 'Pending',
            value: 7,
          },
          {
            label: 'Reported',
            value: 8,
          },
        ],
        newCreateStatusOption: [
          {
            label: 'Active',
            value: 1,
          }
        ],
        //单位数据
        unitOption: [
          {
            label: 'Kyat',
            value: '1',
          },
          {
            label: 'Lakh',
            value: '2',
          },
          {
            label: 'Usd',
            value: '3',
          },
        ],
        // 提交商品后拿到的店铺id，先写个测试数据
        goodsId: '',
        //加载动画
        loadingImage: false,
        //
        otherForm: {},
        //删除图片的id组成的数组
        images: [],
        //记录是新建状态还是编辑状态
        isNewCreate: true,
        //校验
        rules: {
          regionId: [
            {required: true, message: 'please select region', trigger: 'change'}
          ],
          townshipId: [
            {required: true, message: 'please select township', trigger: 'change'}
          ],
          title: [
            {required: true, message: 'title is required', trigger: 'blur'}
          ],
          price: [
            {
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('please enter price'));
                }
                if (/^[0-9]*$/.test(value) === false) {
                  callback(new Error('number only'));
                }
                else if (value > 9999999999) {
                  callback(new Error('cannot exceed 9999999999'));
                }
                else {
                  callback();
                }
              }, trigger: 'blur'
            }
          ],
          firstCategory: [
            {required: true, message: 'please select category1', trigger: 'change'}
          ],
          secondaryCategory: [
            {required: true, message: 'please select category2', trigger: 'change'}
          ],
          thirdCategory: [
            {required: true, message: 'please select category3', trigger: 'change'}
          ],
          condition: [
            {required: true, message: 'please select condition', trigger: 'change'}
          ],
        },
      }
    },
    methods: {
      //错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      //成功消息提示
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'success'
        })
      },
      // 获取二级菜单
      getSecondaryData() {
        this.submitForm.secondaryCategory = ''
        this.submitForm.thirdCategory = ''
        let index
        index = this.categoryData.findIndex((item) => {
          return item.name === this.submitForm.firstCategory
        })
        this.secondaryData = this.categoryData[index].children
        if (this.submitForm.firstCategory) {
          this.categoryData.forEach((item) => {
            if (item.name === this.submitForm.firstCategory) {
              this.submitForm.categoryId = item.id
            }
          })
        }
        this.getPropertyData()
      },
      // 获取三级菜单
      getThirdData() {
        this.submitForm.thirdCategory = ''
        let index
        index = this.secondaryData.findIndex((item) => {
          return item.name === this.submitForm.secondaryCategory
        })
        this.thirdData = this.secondaryData[index].children
        if (this.submitForm.secondaryCategory) {
          this.secondaryData.forEach((item) => {
            if (item.name === this.submitForm.secondaryCategory) {
              this.submitForm.categoryId = item.id
            }
          })
        }
        this.getPropertyData()
      },
      //获取新的catId
      getNewId() {
        if (this.submitForm.thirdCategory) {
          this.thirdData.forEach((item) => {
            if (item.name === this.submitForm.thirdCategory) {
              this.submitForm.categoryId = item.id
            }
          })
        }
        this.getPropertyData()
      },
      //这个函数用来生成一个由propertyData中的propertyId组成的数组
      formatPropertyData(obj) {
        let temp = [];
        for (let i = 0; i < obj.length; i++) {
          //propertyId
          temp[obj[i].id] = '';
        }
        //这个temp里的键名类型是字符串 不是正整数 被坑了。。。。
        this.otherForm = temp
      },
      //获取规格数据
      getPropertyData(res, values) {
        let catId = res ? res : this.submitForm.categoryId
        for (let i = 0; i < this.categoryData.length; i++) { // 属性层级一
          if ((catId === this.categoryData[i].id) && this.categoryData[i].properties) {
            this.formatPropertyData(this.categoryData[i].properties);
            this.propertyData = this.categoryData[i].properties;
          } else {
            if (this.categoryData[i].children.length > 0) {
              for (let j = 0; j < this.categoryData[i].children.length; j++) {  // 属性层级二
                if ((catId === this.categoryData[i].children[j].id) && this.categoryData[i].children[j].properties) {
                  // id为142(对应的是mobiephone)时数据额外处理
                  if (catId == '142') {
                    let arr = [];
                    //先拿到mobile storage数据
                    arr = arr.concat([], this.categoryData[i].children[j].properties);
                    //然后拿到brand数据
                    let brandData = this.phoneBrand.properties
                    //最后根据brandId调后台接口拿到model数据
                    let obj = {
                      "id": 57,
                      "name": "Mobile Model",
                      "values": []
                    }
                    // 编辑初始化页面时,需要获取当前brand对应的model数据
                    if (typeof(values) == 'object' && values.length > 0) {  // 编辑的时候让model属性可以显示出来
                      for (let i = 0; i < values.length; i++) {
                        if (values[i].propertyId == '8') {
                          // 请求model数据
                          getBrandModelData({brandPropertyId: values[i].valueId}).then((res) => {
                            if(res.data.errorID==0){
                              obj['values'] = res.data.object;
                            }
                            else{
                              this.messageToastErr(res.data.message)
                            }
                          }).catch((e) => {
                            console.log(e)
                          })
                        }
                      }
                    }
                    arr.unshift(obj)
                    arr.unshift(brandData);
                    this.formatPropertyData(arr);
                    this.propertyData = arr;
                  }else if(catId == '227'){
                    let arr = [];
                    //先拿到car storage数据
                    arr = arr.concat([], this.categoryData[i].children[j].properties);
                    //最后根据brandId调后台接口拿到model数据
                    let obj = {
                      "id": 55,
                      "name": "Car Model",
                      "values": []
                    }
                    // 编辑初始化页面时,需要获取当前brand对应的model数据
                    if (typeof(values) == 'object' && values.length > 0) {  // 编辑的时候让model属性可以显示出来
                      for (let i = 0; i < values.length; i++) {
                        if (values[i].propertyId == '17') {
                          // 请求model数据
                          getCarModelData({carPropertyId: values[i].valueId}).then((res) => {
                            if(res.data.errorID==0){
                              obj['values'] = res.data.object;
                            }
                            else{
                              this.messageToastErr(res.data.message)
                            }
                          }).catch((e) => {
                            console.log(e)
                          })
                        }
                      }
                    }
                    arr.unshift(obj)
                    arr.unshift(this.carBrand.properties);
                    this.formatPropertyData(arr);
                    this.propertyData = arr;
                  }
                  else {
                    this.formatPropertyData(this.categoryData[i].children[j].properties);
                    this.propertyData = this.categoryData[i].children[j].properties;
                  }
                } else {
                  if (this.categoryData[i].children[j].children.length > 0) {
                    for (let k = 0; k < this.categoryData[i].children[j].children.length; k++) {  // 属性层级三
                      if ((catId === this.categoryData[i].children[j].children[k].id) && this.categoryData[i].children[j].children[k].properties) {
                        this.formatPropertyData(this.categoryData[i].children[j].children[k].properties);
                        this.propertyData = this.categoryData[i].children[j].children[k].properties;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      //额外属性的下拉框获取新数据
      getModelData(propertyId, valueText) {
        if (propertyId == '8') {
          // 清空brandmodel的数据
          this.propertyData[1]['values'] = []
          //清空brandmodel之前选择的数据
          this.otherForm['57'] = ''
          // 根据valuetext找到对应的brandid
          let brandId
          this.phoneBrand['properties'].values.forEach(item => {
            if (item.text == valueText) {
              brandId = item.id
            }
          })
          if (brandId) {
            getBrandModelData({brandPropertyId: brandId})
              .then(res => {
                if (res.data.errorID == 0) {
                  this.propertyData[1]['values'] = res.data.object
                }
                else {
                  this.messageToastErr(res.data.message)
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        }else if(propertyId == '17'){
          // 清空brandmodel的数据
          this.propertyData[1]['values'] = []
          //清空brandmodel之前选择的数据
          this.otherForm['55'] = ''
          // 根据valuetext找到对应的brandid
          let brandId;
          this.carBrand['properties'].values.forEach(item => {
            if (item.text == valueText) {
              brandId = item.id
            }
          })
          if (brandId) {
            getCarModelData(brandId)
              .then(res => {
                if (res.data.errorID == 0) {
                  this.propertyData[1]['values'] = res.data.object
                }
                else {
                  this.messageToastErr(res.data.message)
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        }
      },
      // 获取township数据
      gettownships() {
        this.submitForm.townshipId = ''
        let townData = []
        this.townships.forEach((item) => {
          if (item.regionId === this.submitForm.regionId) {
            townData.push(item)
          }
        })
        this.townshipData = townData
      },
      // 取消提交
      cancelPutForm() {
        this.$router.go(-1)
      },
      //编辑时拿到id，初始化表单
      initForm() {
        this.loadingImage = true
        getShopViewData({goodsId: this.goodsId})
          .then(res => {
            this.loadingImage = false
            let obj = res.data.object
            this.submitForm.status = obj.status
            this.submitForm.title = this.$translateLang(obj.title || '', 'unicodeTozawgyi') || ''
            this.submitForm.price = obj.price
            this.submitForm.priceType = obj.priceType + ''
            this.submitForm.condition = obj.condition + ''
            this.submitForm.desc = this.$translateLang(obj.desc || '', 'unicodeTozawgyi') || ''
            this.submitForm.notes = this.$translateLang(obj.notes || '', 'unicodeTozawgyi') || ''
            // 先拿到regionId，然后获取对应的township数据 最后再对townshipId赋值
            this.submitForm.regionId = obj.regionId
            this.gettownships()
            this.submitForm.townshipId = obj.townshipId
            // 初始化category
            let categoryName = obj.category.categoryName
            let categoryArr = categoryName.split('/')
            this.submitForm.firstCategory = categoryArr[0] || ''
            if(categoryArr[1]){
              this.getSecondaryData()
            }
            this.submitForm.secondaryCategory = categoryArr[1] || ''
            if(categoryArr[2]){
              this.getThirdData()
            }
            this.submitForm.thirdCategory = categoryArr[2] || ''
            //初始化规格
            this.getPropertyData(obj.categoryId, obj.values)
            obj.values.forEach(item => {
              this.otherForm[item.propertyId] = this.$translateLang(item.text || '', 'unicodeTozawgyi') || ''
            })
            //初始化规格上传数据
            this.submitForm.values = []
            //初始化删除图片ID数组
            this.images = []
            //初始化categoryId
            this.submitForm.categoryId = obj.categoryId
            //图片数据初始化
            if (obj.images.length > 0) {
              obj.images.forEach(item => {
                let obj = {}
                obj.id = item.id
                obj.url = item.url
                this.showPhoto[item.sequence] = obj
              })
            }
          })
          .catch(res => {
            this.loadingImage = false
            console.log(res)
          })
      },
      // 正常提交
      uploadSubmitForm() {
        // 先验证是否有首图 没有就弹出消息提示
        if (!this.uploadPhoto[0] && !this.showPhoto[0].id) {
          this.messageToastErr('Cover Photo Is Required')
        }
        else {
          // 然后验证表单信息
          this.$refs['submitForm'].validate((valid) => {
            if (!valid) {
              this.messageToastErr('Wrong Submit')
              return false
            }
            else {
              this.loadingImage = true
              for (let i in this.otherForm) {
                //判断数组里是否有51
                if (i == 51) {
                  this.submitForm.brand = this.otherForm[i]
                }
                let valueId = '';
                // 通过当前选中的 category 所设置的额外属性的json 来进行判断
                for (let j = 0; j < this.propertyData.length; j++) {
                  if (this.propertyData[j].id == i) {
                    if (this.propertyData[j].values.length > 1) {
                      for (let k = 0; k < this.propertyData[j].values.length; k++) {
                        if (this.otherForm[i] == this.propertyData[j].values[k].text) {
                          valueId = this.propertyData[j].values[k].id
                        }
                      }
                    } else {
                      valueId = this.propertyData[j].values[0].id
                      if (this.propertyData[j].id == 51) {
                      }
                    }
                  }
                }
                this.submitForm.values.push({
                  propertyId: i,
                  valueId: valueId,
                  text: this.$translateLang(this.otherForm[i] || '', 'zawgyiTounicode') || ''
                })
              }
              this.submitForm.values = JSON.stringify(this.submitForm.values)
              let formAjaxData = this.submitForm
              //对submitform中输入框的内容进行转码
              formAjaxData.title = this.$translateLang(this.submitForm.title || '', 'zawgyiTounicode') || ''
              formAjaxData.desc = this.$translateLang(this.submitForm.desc || '', 'zawgyiTounicode') || ''
              formAjaxData.notes = this.$translateLang(this.submitForm.notes || '', 'zawgyiTounicode') || ''
              formAjaxData.userId = this.userId
              let config = {
                'Content-Type': 'multipart/form-data'
              }
              //编辑
              if (!this.isNewCreate) {
                //添加goodsId字段
                formAjaxData.goodsId = this.goodsId
                //添加被删除图片id组成的数组 images字段
                formAjaxData.images = JSON.stringify(this.images)
                let params = Qs.stringify(formAjaxData)
                editFormInfo(params, config)
                  .then((res) => {
                    if (res.data.errorID === 0) {
                      this.messageToastSuccess('Edit Success')
                      this.loadingImage = false
                      //表单上传成功之后直接上传图片
                      this.sendFormPhotos(this.goodsId)
                    }
                    else {
                      this.loadingImage = false
                      this.messageToastErr(res.data.message)
                    }
                  })
                  .catch((error) => {
                    this.loadingImage = false
                    this.messageToastErr('error,please try again later')
                  })
              }
              // 没有id就是新增
              else {
                let params = Qs.stringify(formAjaxData)
                uploadFormInfo(params, config)
                  .then((res) => {
                    this.loadingImage = false
                    if (res.data.errorID === 0) {
                      this.messageToastSuccess('New Create Success')
                      if (res.data.object.id) {
                        this.goodsId = res.data.object.id
                        //上传图片 有就上传 没有就提示表单提交成功
                        this.sendFormPhotos(this.goodsId)
                      }
                    }
                    else {
                      this.loadingImage = false
                      this.messageToastErr(res.data.message)
                    }
                  })
                  .catch((error) => {
                    console.log(error)
                    this.loadingImage = false
                    this.messageToastErr('error,please try again later')
                  })
              }
            }
          })
        }
      },
      // 多图上传
      sendFormPhotos(id) {
        let showPhotos = []
        let fileName = 'adPhoto'
        showPhotos = this.uploadPhoto
        let formData = new FormData()
        //  是否有图片提交，有则提交图片，没有则显示表单提交成功信息
        let isToUpload = false
        for (let i = 0; i < showPhotos.length; i++) {
          if (showPhotos[i]) {
            formData.append(fileName + '_' + i, showPhotos[i])
            isToUpload = true
          }
        }
        // 上传图片
        if (isToUpload) {
          this.loadingImage = true
          formData.append('goodsId', id)
          let config = {
            'Content-Type': 'multipart/form-data'
          }
          //上传二进制图片文件
          this.loadingImage = true
          uploadShopAdPhotos(formData, config).then((res) => {
            this.loadingImage = false
            if (res.data) {
              this.reLoadPage()
              if (res.data.errorID === 0) {
                this.loadingImage = false
              }
              else {
                this.loadingImage = false
                this.messageToastErr('Upload picture failed, please try again later')
              }
            }
          })
            .catch((error) => {
              this.loadingImage = false
              console.log(error)
              this.messageToastErr('error, please try again later')
            })
        } else {
          this.reLoadPage()
        }
      },
      //重置表单
      resetForm(submitForm) {
        this.$refs[submitForm].resetFields()
        this.submitForm.status = 1
        this.submitForm.firstCategory = ''
        this.submitForm.secondaryCategory = ''
        this.submitForm.thirdCategory = ''
        this.submitForm.price = ''
        this.submitForm.desc = ''
        this.submitForm.values = []
        this.propertyData = [],
          this.otherForm = {},
          this.submitForm.regionId = ''
        this.submitForm.townshipId = ''
        this.submitForm.notes = ''
        this.showPhoto = [
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
          {url: '', id: ''},
        ]
        this.uploadPhoto = []
      },
      //重新加载页面
      reLoadPage() {
        // if (this.isNewCreate) {
        //   console.log('是新增状态，重置表单为默认设置')
        //   this.resetForm('submitForm')
        // } else {
        //   console.log('是编辑状态，初始化表单')
        //   this.initForm()
        // }
        // console.log('reload')
        this.$router.go(-1)
      },
      // 获取图片文件
      getFile($event, index) {
        let file = $event.target.files[0];
        let reader = new FileReader()
        //reader.onload 后面接一个立即执行函数并且把file作为参数传进去
        reader.onload = ((theFile) => {
          return (e) => {
            this.setImageCompress(e, theFile, (imgObj) => {
              this.$set(this.showPhoto, index, {url: imgObj.photoUrl, id: ''})
              this.$set(this.uploadPhoto, index, imgObj.photoBlob)
            })
          }
        })(file)
        reader.readAsDataURL(file)
      },
      // 压缩图片
      setImageCompress(e, theFile, callback) {
        let img = new Image()
        img.src = e.target.result;
        let canvas = document.createElement('canvas')
        let context = canvas.getContext('2d')
        let self = this
        img.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width
          let originHeight = this.height
          // 最大尺寸限制
          let maxWidth = 1000
          let maxHeight = 1000
          // 目标尺寸
          let targetWidth = originWidth
          let targetHeight = originHeight
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth
              targetHeight = Math.round(maxWidth * (originHeight / originWidth))
            } else {
              targetHeight = maxHeight
              targetWidth = Math.round(maxHeight * (originWidth / originHeight))
            }
          }
          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          // canvas转为blob并上传
          canvas.toBlob((blob) => {
            let srcUrl = URL.createObjectURL(blob)
            let imgObj = {
              photoUrl: srcUrl,
              photoBlob: blob,
              name: name,
            }
            callback(imgObj);
          }, 'image/jpeg', 0.9)
        }
      },
      // 删除图片 photos
      delImage(e, id) {
        this.showPhoto.splice(e, 1, '')
        this.uploadPhoto.splice(e, 1, '')
        if (id) {
          this.images.push(id)
        }
      },
    },
    mounted() {
      window.scrollTo(0, 0)
      this.goodsId = this.$route.query.goodsId || ''
      if (this.goodsId) {
        this.isNewCreate = false
        this.initForm()
      }
      if (this.$route.query.userId) {
        this.userId = this.$route.query.userId
      }
    },
  };
</script>


<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    /*padding-top: 20px;*/
    border-bottom: 1px solid #eee;
  }

  .line-form {
    border-top: 1px solid #eee;
  }

  .more-box,
  .list-items-box {
    padding-top: 20px;
    padding-bottom: 10px;
  }

  .list-items-box {
    /*margin-right: 10%;*/
  }

  .list-items-box .el-form--inline.el-form--label-top .el-form-item__content {
    display: inline-block;
  }

  .change-status {
    font-size: 14px;
    margin-right: 10px;
  }

  .options {
    padding: 0px 0 20px 0;
  }

  .container-padding {
    padding: 0 40px;
  }

  .list-notes {
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
  }

  .new-user-dialog .el-form-item {
    margin-bottom: 0 !important;
  }

  .activity-list-page .el-checkbox + .el-checkbox {
    margin-left: 0 !important;
    margin-right: 30px !important;
  }

  /*新增样式*/
  .upload-box {
    padding: 0 15px;
    height: 96px;
    margin: 10px 0;
  }

  .photos-box {
    width: 100%;
    display:flex;
  }

  .photos-box .color-box {
    position: relative;
    width: 77px;
    height: 77px;
    margin-right: 15px;
    margin-bottom: 15px;
    border-radius: 5px;
    overflow: hidden;
  }

  .photos-box .color-show {
    display: inline-block;
    flex-wrap: wrap;
    padding: 0 0;
  }

  .photos-box .color-box img {
    width: 100%;
    height: 100%;
  }

  .photos-box .color-box a {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: none;
  }

  .photos-box .color-box:hover a {
    display: block;
  }

  .photos-box .color-box .glyphicon {
    width: 100%;
    height: 100%;
    color: #aeaeae;
    display: block;
    text-align: center;
    line-height: 77px;
    background: rgba(0, 0, 0, .4);
    border-radius: 5px;
  }

  .photos-box .color-box a.add-photos {
    display: block;
    box-sizing: border-box;
    border: 1px dashed #D8DCE5;
    border-radius: 5px;
  }

  .photos-box .color-box a.add-photos:hover {
    border: 1px dashed #409EFF;
  }

  .glyphicon {
    width: 100%;
    height: 100%;
    color: #aeaeae;
    display: inline-block;
    text-align: center;
    line-height: 77px;
    background: rgba(0, 0, 0, .4);
    border-radius: 5px;
  }

  .photos-box .color-box .add-photos .glyphicon {
    background: rgba(255, 255, 255, .7);
  }

  .upload-photos::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }

  .price-require {
    position: relative;
  }

  .price-require::before {
    position: absolute;
    content: '*' !important;
    color: #f56c6c;
    left: -8px;
    top: 6px;
  }
</style>
